<!DOCTYPE html>
<html>
<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>传智健康</title>
    <meta name="description" content="传智健康">
    <meta name="keywords" content="传智健康">
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../plugins/elementui/index.css">
    <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../css/style.css">
    <script type="text/javascript"
            src="http://api.map.baidu.com/api?v=2.0&ak=cfLNgKV8p0PgWwow9g4qrcAPZaeQa7I7"></script>
</head>
<body class="hold-transition">
<div id="app">
    <div class="content-header">
        <h1>首页
            <small>公司分布图</small>
        </h1>
        <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>公司分布图</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
    <div class="app-container">
        <div class="box">
            <template>
                <el-tabs v-model="activeName">
                    <el-tab-pane label="分布图" name="first">
                        <div id="allmap1"></div>
                    </el-tab-pane>
                    <el-tab-pane label="详情信息" name="second">
                        <div class="filter-container">
                            <el-input placeholder="公司地址" v-model="pagination.queryString" style="width: 200px;"
                                      class="filter-item"></el-input>
                            <el-button @click="findPage()" class="dalfBut">查询</el-button>
                            <el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
                        </div>
                        <el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
                            <el-table-column type="index" align="center" label="序号"></el-table-column>
                            <el-table-column prop="address" label="公司地址" align="center"></el-table-column>
                            <el-table-column prop="longitude" label="所在经度" align="center"></el-table-column>
                            <el-table-column prop="latitude" label="所在纬度" align="center"></el-table-column>
                            <el-table-column label="操作" align="center">
                                <template slot-scope="scope">
                                    <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="pagination-container">
                            <el-pagination
                                    class="pagiantion"
                                    @current-change="handleCurrentChange"
                                    :current-page="pagination.currentPage"
                                    :page-size="pagination.pageSize"
                                    layout="total, prev, pager, next, jumper"
                                    :total="pagination.total">
                            </el-pagination>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </template>
            <!-- 新增标签弹层 -->
            <div class="add-form">
                <el-dialog title="新增地址" :before-close="handleDialogClose" :visible.sync="dialogFormVisible" width="650px">
                    <el-form ref="dataAddForm" label-position="right" label-width="100px">
                        <el-row>
                            <el-col :span="15">
                                <el-input v-model="shopAddress" type="text" id="suggestId"
                                          placeholder="输入地址"></el-input>
                                <div id="searchResultPanel"
                                     style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
                            </el-col>
                            <el-button type="primary" @click="handleAdd()">确定添加</el-button>
                        </el-row>
                        <el-row>
                            <div id="allmap2"></div>
                        </el-row>
                    </el-form>
                </el-dialog>
            </div>
        </div>
    </div>
</div>
</body>
<!-- 引入组件库 -->
<script src="../js/vue.js"></script>
<script src="../plugins/elementui/index.js"></script>
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script>

    var vue = new Vue({
        el: '#app',
        data: {
            activeName: 'first',//选项卡名称 默认第一个
            pagination: {//分页相关模型数据
                currentPage: 1,//当前页码
                pageSize: 10,//每页显示的记录数
                total: 0,//总记录数
                queryString: null//查询条件
            },
            dataList: [],//当前页要展示的分页列表数据
            // address: "",    //地址
            // longitude: "", // 经度
            // latitude: "", // 纬度
            dialogFormVisible: false,//增加表单是否可见
            shopAddress: "",    //详细地址
        },

        //钩子函数
        mounted() {
            // 百度地图API功能
            var map = new BMap.Map("allmap1");
            map.centerAndZoom("武汉", 12);
            map.enableScrollWheelZoom(true);
            var index = 0;
            var myGeo = new BMap.Geocoder();
            var adds = [];

            //获取所有地址
            axios.post("/address/allAddress.do").then((resp) => {
                adds = resp.data;
                //console.log(adds);
                //调用方法 标点
                bdGEO();
            });


            function bdGEO(){
                if (index < adds.length) {
                    var add = adds[index];
                    geocodeSearch(add);
                    index++;
                }
            }
            function geocodeSearch(add){
                if(index < adds.length){
                    setTimeout(bdGEO,400);
                }
                myGeo.getPoint(add, function(point){
                    if (point) {
                        var address = new BMap.Point(point.lng, point.lat);
                        addMarker(address,new BMap.Label(add,{offset:new BMap.Size(20,-10)}));
                    }
                }, "武汉市");
            }
            // 编写自定义函数,创建标注
            function addMarker(point,label){
                var marker = new BMap.Marker(point);
                map.addOverlay(marker);
                marker.setLabel(label);
            }

        },
        //钩子函数，VUE对象初始化完成后自动执行
        created() {
            this.findPage();
        },


        methods: {
            //百度搜索 下拉菜单点击触发
            setPlace(map,myValue,a) {
                map.clearOverlays();    //清除地图上所有覆盖物
                var addressParam;

                function myFun() {
                    var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果 lng 经度 lat 纬度
                    map.centerAndZoom(pp, 18);
                    map.addOverlay(new BMap.Marker(pp));    //添加标注
                    // console.log(pp);
                    // console.log('address:' + myValue,'lng:' + pp.lng + 'lat:' + pp.lat);
                    var strAddress = myValue;

                    a.address = strAddress;
                    a.longitude = pp.lng; // 经度
                    a.latitude = pp.lat; // 纬度

                    // alert(a.address);
                    // alert(a.longitude);
                    // alert(a.latitude);

                }

                var local = new BMap.LocalSearch(map, { //智能搜索
                    onSearchComplete: myFun
                });
                local.search(myValue);
            },


            //添加
            handleAdd() {
                // alert(this.address);
                // alert(this.longitude);
                // alert(this.latitude);
                var param = {
                    address: this.address,
                    longitude: this.longitude, // 经度
                    latitude: this.latitude // 纬度
                };
                axios.post("/address/add.do",param).then((resp) => {
                    if (resp.data.flag) {
                        this.$message.success(resp.data.message);
                    }else {
                        this.$message.error(resp.data.message);
                    }
                    this.shopAddress = "";
                    this.dialogFormVisible = false;
                    this.findPage();
                })
            },
            //分页查询
            findPage() {
                //发送ajax请求，提交分页相关请求参数（页码、每页显示记录数、查询条件）
                var param = {
                    currentPage: 1,
                    pageSize: this.pagination.pageSize,
                    queryString: this.pagination.queryString
                };
                axios.post("/address/findPage.do", param).then((res) => {
                    if (res.data.flag) {

                        this.$message.success(res.data.message);
                        //解析Controller响应回的数据，为模型数据赋值
                        this.pagination.total = res.data.data.total;
                        this.dataList = res.data.data.rows;
                        console.log(this.dataList);
                    } else {
                        this.$message.error(res.data.message);
                    }

                });
            },
            // 重置表单
            resetForm() {

            },
            // 弹出添加窗口
            handleCreate() {
                //弹出新增窗口
                this.dialogFormVisible = true;
                this.resetForm();
                this.$nextTick(() => {
                    this.initMap(this);
                });
            },

            //切换页码
            handleCurrentChange(currentPage) {
                //发送ajax请求，提交分页相关请求参数（页码、每页显示记录数、查询条件）
                var param = {
                    currentPage: currentPage,
                    pageSize: this.pagination.pageSize,
                    queryString: ""
                };
                axios.post("/address/findPage.do", param).then((res) => {
                    if (res.data.flag) {
                        this.$message.success(res.data.message);
                        //解析Controller响应回的数据，为模型数据赋值
                        this.pagination.total = res.data.total;
                        this.dataList = res.data.rows;
                    } else {
                        this.$message.error(res.data.message);
                    }

                });
            },

            showMessage(r) {
                if (r == 'Error: Request failed with status code 403') {
                    //权限不足
                    this.$message.error('无访问权限');
                    return;
                } else {
                    this.$message.error('未知错误');
                    return;
                }
            },

            // 删除
            handleDelete(row) {//row其实是一个json对象，
                this.$confirm('此操作将永久删除地址, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.post("/address/deleteAddress.do?id="+row.id).then((resp) => {
                        if (resp.data.flag) {
                            this.$message({
                                type: 'success',
                                message: resp.data.message,
                            });
                            this.findPage();
                        } else {
                            this.$message({
                                type: 'error',
                                message: resp.data.message,
                            });
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //对话框地图初始化
            initMap(a) {
                function G(id) {
                    return document.getElementById(id);
                }

                var map = new BMap.Map("allmap2");
                map.centerAndZoom("武汉", 12);                   // 初始化地图,设置城市和地图级别。

                var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
                    {
                        "input": "suggestId"
                        , "location": map
                    });

                ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
                    var str = "";
                    var _value = e.fromitem.value;
                    var value = "";
                    if (e.fromitem.index > -1) {
                        value = _value.province + _value.city + _value.district + _value.street + _value.business;
                    }
                    str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

                    value = "";
                    if (e.toitem.index > -1) {
                        _value = e.toitem.value;
                        value = _value.province + _value.city + _value.district + _value.street + _value.business;
                    }
                    str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
                    G("searchResultPanel").innerHTML = str;
                });

                var myValue;
                ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
                    var _value = e.item.value;
                    myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
                    G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
                    a.setPlace(map,myValue,a);
                });

            },

            //弹窗关闭的回调方法
            handleDialogClose(){
                this.shopAddress = "";  //清空输入框数据
                this.dialogFormVisible = false;     //关闭对话框
            },
        }
    })
</script>
</html>